<template>
  <el-dialog class="assign-role" title="分配角色" :visible="showRoleDialog" @open="dialogOpen">
    <!-- el-checkbox-group选中的是 当前用户所拥有的角色  需要绑定 当前用户拥有的角色-->
    <el-checkbox-group>
      <!-- 选项 -->
      <el-checkbox-group v-model="roleIds">
        <el-checkbox v-for="item in list" :key="item.id" :label="item.id">
          {{ item.name }}
        </el-checkbox>
      </el-checkbox-group>
    </el-checkbox-group>
    <template #footer>
      <el-button type="primary" size="small" @click="hSubmit">确定</el-button>
      <el-button size="small" @click="hCancel">取消</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { getRoleList } from '@/api/setting'
import { getUserDetailById } from '@/api/user'
import { assignRoles } from '@/api/employees.js'
export default {
  props: {
    showRoleDialog: {
      type: Boolean,
      default: false
    },

    // 用户的id 用来查询当前用户的角色信息
    userId: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      list: [],
      roleIds: []
    }
  },
  mounted() {
    this.loadRoleList()
  },
  methods: {
    async hSubmit() {
      await assignRoles({
        id: this.userId,
        roleIds: this.roleIds
      })
      this.$message.success('保存成功')

      // 关闭弹框
      this.$emit('update:showRoleDialog', false)
    },
    dialogOpen() {
      this.loadUserDetailById()
    },
    closeDialog() {
      this.$emit('update:showRoleDialog', false)
    },
    async loadRoleList() {
      const data = await getRoleList({ page: 1, pageSize: 100 })
      this.list = data.rows
    },
    async loadUserDetailById() {
      const res = await getUserDetailById(this.userId)
      this.roleIds = res.roleIds
    },
    hCancel() {
      this.$emit('update:showRoleDialog', false)
    }
  }
}
</script>
